import React, { useEffect } from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import Login from "./pages/login.jsx";
import TeacherForm from "./pages/teacherForm.jsx";
import CompanyForm from "./pages/companyForm.jsx";
import Search from "./pages/search.jsx";
import { checkTokenApi, getToken } from "./apis/wx.js";
import VConsole from "vconsole";

const queryParams = new URLSearchParams(window.location.search);
const debugParams = queryParams.get("debug");
if (debugParams == 1) {
  localStorage.setItem("debug", 1);
}
if (debugParams == 0) {
  localStorage.setItem("debug", 0);
}
if (localStorage.getItem("debug") == 1) {
  const vConsole = new VConsole();
}

const router = createBrowserRouter([
  {
    path: "/",
    element: <TeacherForm></TeacherForm>,
  },
  {
    path: "/teacher",
    element: <TeacherForm></TeacherForm>,
  },
  {
    path: "/company",
    element: <CompanyForm></CompanyForm>,
  },
  {
    path: "/search",
    element: <Search></Search>,
  },
]);

const App = () => {
  const appid = "wx120b90e434ae622f";
  const serect = "2d725c8804ad9a1ff03048ebef488bac";
  const redirect_uri = window.location.href;

  const getCordUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=#wechat_redirect`;

  const checkToken = async () => {
    const wxToken = sessionStorage.getItem("accessToken");
    // 没token
    if (!wxToken) {
      const queryParams = new URLSearchParams(window.location.search);

      const code = queryParams.get("code");
      console.log("[code]", code);
      // 重定向后获取code解析
      if (code) {
        console.log("[code]", code);
        const resp = await getToken({
          type: 31,
          code,
          state: "1",
          scope: "snsapi_base",
        });

        const { userId, accessToken, openid } = resp?.data?.data;
        console.log("[token]", resp?.data);
        // 调后端接口 拿 token
        if (accessToken) sessionStorage.setItem("accessToken", accessToken);
        if (openid) sessionStorage.setItem("openid", openid);
        if (userId) sessionStorage.setItem("userId", userId);
      } else {
        window.location.href = getCordUrl;
      }
    }

    //   else {
    //     let isValid = true;
    //     // check token
    //     const resp = await checkTokenApi({
    //       access_token: sessionStorage.getItem("accessToken"),
    //       openid: sessionStorage.getItem("openid"),
    //     });
    //     console.log(
    //       "[checkTokenApi]",
    //       {
    //         access_token: sessionStorage.getItem("accessToken"),
    //         openid: sessionStorage.getItem("openid"),
    //       },
    //       resp
    //     );

    //     isValid = resp?.errcode == 0;
    //     if (!isValid) {
    //       window.location.href = getCordUrl;
    //     }
    //   }
  };

  useEffect(() => {
    checkToken();

    window.addEventListener("beforeunload", function () {
      sessionStorage.removeItem("accessToken");
      sessionStorage.removeItem("openid");
      sessionStorage.removeItem("userId");
    });
  }, []);

  return (
    <div id="root">
      <React.StrictMode>
        <RouterProvider router={router} />
      </React.StrictMode>

      <div
        className="flex items-center justify-center mt-[40px] text-[14px] pb-[30px]"
        style={{ color: "rgba(0,0,0,0.65)" }}
      >
        <a href="https://beian.miit.gov.cn" target="_blank">
          京ICP备2024070939号-1
        </a>
      </div>
    </div>
  );
};

ReactDOM.createRoot(document.getElementById("root")).render(<App></App>);
